package com.sxm.yiwei.fragments;


import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.activitis.ForgetPassWordActivity;
import com.sxm.yiwei.activitis.UserUpActivity;
import com.sxm.yiwei.utils.AESUtil;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import cn.jpush.android.api.JPushInterface;

/**
 * A simple {@link Fragment} subclass.
 */
public class LoginFragment extends Fragment  implements View.OnClickListener{


    private EditText inphone;
    private EditText inword;
    private ImageView phoneClear;
    private ImageView wordClear;
    private TextView forgetWord;
    private Button userlogin;
    private SharedPreferences sharedPreferences;
    private String rid;
    private String appid;
    private String longitude;
    private String latitude;
    private String phone;
    private String word;
    private String userId;
    private String token;
    private String aWord;

    public LoginFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_login, container, false);
        sharedPreferences = getActivity().getSharedPreferences("userlogin", Context.MODE_PRIVATE);

        longitude = sharedPreferences.getString("longitude", "");
        latitude = sharedPreferences.getString("latitude", "");
        initLoginFview(view);
        return view;

    }

    // 用户登陆
    public void UserLogin(String app,String id) {
       // getInPutData();
        try {
            aWord = AESUtil.encryptAES(word);
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/user/login");// 登陆接口
        params.addHeader("Content-Type","application/json");
        params.addHeader("appId",app);
        final JSONObject jsonObject = new JSONObject();
        jsonObject.put("username",phone);
        jsonObject.put("password", aWord);
        jsonObject.put("registrationId",id);
        jsonObject.put("longitude",longitude);
        jsonObject.put("latitude",latitude);
        params.setBodyContent(jsonObject.toJSONString());
        final String finalAWord = aWord;

        Log.d("tag", "UserLogin: 登陆--"+app+"//"+id+"//"+longitude+"//"+latitude+"//"+aWord+"//"+phone);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d("tag", "onSuccess: 登陆---"+result);
                com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
                String status = obj.getString("status");
                if (status.equals("1")){
                    String data = obj.getString("data");
                    com.alibaba.fastjson.JSONObject obj1 = JSON.parseObject(data);
                    userId = obj1.getString("userId");
                    token = obj1.getString("token");
                    SharedPreferences.Editor edit = sharedPreferences.edit();
                    edit.putString("userId", userId);
                    edit.putString("token", token);
                    edit.putString("phone", phone);
                    edit.putString("word", aWord);
                    edit.commit();

                    getActivity().finish();
                }else{
                    String failure = obj.getString("failure");
                    if (failure.equals("1002")){
                        Toast.makeText(getActivity(), "用户名或密码错误", Toast.LENGTH_SHORT).show();
                    }else if (failure.equals("1003")){
                        Toast.makeText(getActivity(), "账号被禁用", Toast.LENGTH_SHORT).show();
                    }else if (failure.equals("1009")){
                        Toast.makeText(getActivity(), "手机号未注册", Toast.LENGTH_SHORT).show();
                    }else {}

            }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag", "onError: 登陆--"+ex);

              //  Toast.makeText(getActivity(), "登陆失败,密码或账号错误", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("tag", "onCancelled: cex--"+cex);
            }
            @Override
            public void onFinished() {
            }

        });
    }
        // 获取输入内容
    private void getInPutData() {
        phone = String.valueOf(inphone.getText());
        word = String.valueOf(inword.getText());
        appid = sharedPreferences.getString("appid", "");
        rid = JPushInterface.getRegistrationID(getActivity());
    }

        // 初始化控件
    private void initLoginFview(View view) {
        inphone = (EditText) view.findViewById(R.id.login_inphone);
        inword = (EditText) view.findViewById(R.id.login_inword);
        phoneClear = (ImageView) view.findViewById(R.id.login_phoneclear);
        wordClear = (ImageView) view.findViewById(R.id.login_wordclear);
        forgetWord = (TextView) view.findViewById(R.id.login_forgetword);
        userlogin = (Button) view.findViewById(R.id.login_userlogin);

        phoneClear.setOnClickListener(this);
        wordClear.setOnClickListener(this);
        forgetWord.setOnClickListener(this);
        userlogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.login_phoneclear:
                inphone.setText("");
                break;
            case R.id.login_wordclear:
             inword.setText("");
                break;
            case R.id.login_userlogin:
                getInPutData();
                if (isPhoneNumber(phone)){
                    if (word.equals("")){
                        Toast.makeText(getActivity(), "请输入密码", Toast.LENGTH_SHORT).show();
                    }else {
                        UserLogin(appid,rid);
                    }
                }else {
                    Toast.makeText(getActivity(), "账号错误", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.login_forgetword:

                startActivity(new Intent(getActivity(), ForgetPassWordActivity.class));
                break;
        }
    }
    // 验证手机号
    private boolean isPhoneNumber(String phone) {
        String isPhone = "[1][34578]\\d{9}";
        boolean matches = phone.matches(isPhone);

        return matches;

    }
}
